package by.qizer.supercamp.dao;

import by.qizer.supercamp.domain.Guard;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Pribytkoyski Alexey
 *         User: qizer
 *         Date: 04.04.12
 */

@Repository
public class GuardDAOImpl implements GuardDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addGuard(Guard guard) {
        if (checkGuard(guard)) {
            sessionFactory.getCurrentSession().save(guard);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Guard> listGuards() {
        return sessionFactory.getCurrentSession().createQuery("from Guard").list();
    }

    public void removeGuard(Integer id) {
        Guard guard = (Guard) sessionFactory.getCurrentSession().load(Guard.class, id);
        if (null != guard) {
            sessionFactory.getCurrentSession().delete(guard);
        }
    }

    private boolean checkGuard(Guard guard) {
        String lastName = guard.getLastName();
        String firstName = guard.getFirstName();
        String phone = guard.getPhone().trim();

        if (phone.length() < 7) {
            return false;
        } else {
            int lengthPhone = phone.length();
            phone = phone.substring(lengthPhone - 7, lengthPhone);
        }

        String hql = "from Guard where lastName='" + lastName + "'" +
                "and firstName='" + firstName + "'" +
                "and phone like '%" + phone + "'";

        List<Guard> answer = sessionFactory.getCurrentSession().createQuery(hql).list();

        if (answer.isEmpty()) {
            return true;
        }

        return false;
    }
}
